<template>
  <div>
    <div >展示</div>
    <div><el-button size="small" @click="editTools.open">编辑</el-button></div>

    <el-dialog
        title="公式编辑"
        v-model="editTools.state.visible" append-to-body
    :before-close="editTools.beforeClose"
    >
      <div></div>
      <div class="z-wang-editor z-wang-textarea">
        <!--    {{value}}-->
        <div :id="toolbarID"></div>
        <div :id="editorID"></div>
      </div>
      <el-row>
        <el-col :span="6">
          <div>变量</div>
          <div>
            <el-tree :data="editTools.varTools.state.tree" default-expand-all
                     :props="editTools.varTools.state.defaultProps"
                     @node-click="editTools.varTools.handleNodeClick" />
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
// import { Boot } from '@wangeditor/editor'
import {nextTick, reactive} from "vue";



function editVars(props, ctx, options) {
  let state = reactive({
    visible: false,
    defaultProps: {
      children: 'children',
      label: 'label',
    },
    tree: []
  })
  state.tree = [
    {
      label: 'Level one 1',
      children: [
        {
          label: 'Level two 1-1',
        },
        {
          label: 'Level two 1-2',
        },
      ],
    },
  ]
  function handleNodeClick(data, node) {
    if (node.isLeaf) {
      let editor = options.getEditor()

      console.log('handleNodeClick', data, editor.getSelectionPosition())
      // editor.focus()
      // editor.select(editor.selection ?? [])
      // editor.selectAll()
      // editor.dangerouslyInsertHtml(`<text>${data.label}</text>`)
      // editor.updateView()
      // editor.clear()
      // const node = { type: 'text1', children: [{text: data.label}]}
      // editor.insertNode(node)
// 全选并删除
      let SlateTransforms = wangEditor.SlateTransforms
      editor.select([])
      editor.deleteFragment()
      SlateTransforms.setNodes(editor, { type: 'paragraph' }, { mode: 'highest' })
// 1.2 插入内容
      editor.dangerouslyInsertHtml('<div>你的文章内容</div>')
    }
  }
  return {
    state,
    handleNodeClick,
  }
}

function editPart(props, ctx, options) {
  let varTools = editVars(props, ctx, options)

  let state = reactive({
    visible: false
  })

  function open() {
    state.visible = true;
    nextTick(() => {
      options.init('options')
    })
  }

  function beforeClose(done) {
    options.destory()
    done()
  }

  return {
    state,
    varTools,
    beforeClose,
    open
  }
}

export default {
  name: 'ZWangTextarea',
  props: {
    value: String
  },
  setup(props, ctx) {
    const {createEditor, createToolbar } = window.wangEditor

    let editorID = 'z_editor_e__' + ZY.rid()
    let toolbarID = 'z_editor_t__' + ZY.rid()
    let editor;
    let toolbar;
    let locks;

    const editorConfig  = {}
    editorConfig.placeholder = '请输入内容'
    editorConfig.onChange = (editor) => {
      // 当编辑器选区、内容变化时，即触发
      // console.log('content', editor.children)
      // console.log('html', editor.getHtml())
      let html =  editor.getHtml();
      let parser = new DOMParser();
      let b = parser.parseFromString(html, 'text/html');
      let all = b.body.getElementsByTagName("*");
      all.forEach(ele => {
        ele.classList.add('w-e-' + ZY.lodash.kebabCase(ele.tagName))
      })

      ctx.emit('val-change', {
        content: ZY.JSON5.parse(ZY.JSON5.stringify(editor.children)),
        html:b.body.innerHTML
      })
    }

    function initEditor(content = []) {
      editor = createEditor({
        selector: "#" + editorID,
        config: editorConfig,
        content: content, // 默认内容，下文有解释
        // mode: 'simple' // 或者 'simple' ，下文有解释
      });

      // console.log(editor.getAllMenuKeys())

      const toolbarConfig = {
        toolbarKeys: [
          // 菜单 key
          // 'headerSelect',

          // 分割线
          // '|',

          // 菜单 key
          // 'bold', 'italic',

          // 继续配置其他菜单...
        ]
      }

      // 创建工具栏
      toolbar = createToolbar({
        editor,
        selector: '#' + toolbarID,
        config: toolbarConfig,
        mode: 'simple' // 或者 'simple' ，下文有解释
      })
    }

    function destory() {
      // console.log(editor)
      if (editor && editor.destory) {
        editor.destory()
      }
    }

    let editTools = editPart(props, ctx, {
      getEditor() {
        return editor
      },
      init,
      destory
    })


    function init(newVal) {
      if (!locks) {
        // console.log('sdsdsds', newVal)
        locks  = true
        // let content = []
        // try {
        //   let obj = ZY.JSON5.parse(newVal)
        //   if (obj.content) {
        //     content = obj.content
        //   }
        // } catch (e) {
        //   //
        // }
        initEditor()
        // editor.dangerouslyInsertHtml('sdsds')
      }
    }

    return {
      editorID,
      editTools,
      init,
      toolbarID
    }
  }
}
</script>
